package com.atguigu.tingshu.order.handle;

import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author atguigu-mqx
 * @ClassName RedisDelayHandle
 * @description: TODO
 * @date 2023年12月11日
 * @version: 1.0
 */
@Component
@Slf4j
@EnableScheduling
public class RedisDelayHandle {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private RedissonClient redissonClient;


    //    @Scheduled(cron = "* * * * * ?")
    //    public void task(){
    //        System.out.println("hello.");
    //    }
    //    xxl-job 分布式定时任务调度中心. web 界面。1,3！

    //  发送消息 offer(); 接收消息 take();
    //  表示初始化操作.  不停的监听延迟消息队列.
    @PostConstruct
    public void orderCancel(){
        //  创建线程.
        new Thread(()->{
            while (true){
                try {
                    //  从队列中获取.
                    RBlockingQueue<Object> blockingQueue = redissonClient.getBlockingQueue(KafkaConstant.QUEUE_ORDER_CANCEL);
                    //  获取订单Id
                    String orderId = (String) blockingQueue.take();
                    if(!StringUtils.isEmpty(orderId)){
                        //  获取订单对象
                        OrderInfo orderInfo = orderInfoService.getById(orderId);
                        //                        if (orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_CANCEL) ||
                        //                                orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_PAID)){
                        //                            return;
                        //                        }
                        if (orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)){
                            //  调用取消订单方法.
                            orderInfoService.orderCancel(Long.parseLong(orderId));
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }


}
